"use strict";

define(function() {
    return (angular, api) => {
        var app = angular.module('rsms', [ 'ngMaterial' ]);

        app.config(function($mdThemingProvider, $mdIconProvider) {
            $mdThemingProvider.theme('default')
                    .primaryPalette('blue');

            // load icons
            [
                'home',
                'menu',
                'more-vert',
                'account-switch',
                'account-alert',
                'account-key',
                'account-multiple',
                'account-convert',
                'account-clipboard',
                'account-network',
                'back',
                'refresh',
                'plus',
                'check',
                'close',
                'cancel',
                'receipt',
                'trending-up',
                'comment',
                'comment-more',
                'motorbike',
                'cash',
                'list-ordered',
            ].forEach(icon => $mdIconProvider.icon(icon, './icons/' + icon + '.svg'));
        });

        app.controller('app-controller', function($mdSidenav,
                $mdMedia, $scope, $mdComponentRegistry, $mdToast, $mdDialog) {
            var _ = this;

            function popup(msg, delay)
            {
                var toast = $mdToast.simple()
                        .textContent(msg)
                        .position('top right');
                if (delay != null) toast = toast.hideDelay(delay);
                $mdToast.show(toast);
            }

            function prompt_dialog(info, open_from)
            {
                $mdDialog.show({
                    templateUrl: 'prompt-dialog',
                    clickOutsideToClose: true,
                    controller: 'prompt-dialog-controller as dialog',
                    openFrom: open_from,
                    locals: { info: info },
                });
            }

            _.busy = null;
            _.name = api.name;
            _.username = api.username;
            _.role = api.role;
            _.api_base = api.base;
            _.roles = api.roles;

            _.set_busy = function(busy) { _.busy = (busy == null ? "" : busy); };
            _.set_idle = function() { _.busy = null; };

            _.toolbar_show_icons = function() { return $mdMedia('gt-md'); };
            _.menu_lock_open = function() {
                var big = $mdMedia('gt-xs');
                if (big && _.menu_opened()) _.close_menu();
                return big;
            };

            _.menu_opened = function() {
                return false;
            };
            _.open_menu = function() {};
            _.close_menu = function() {};

            $mdComponentRegistry.when('left').then(function(nav) {
                _.menu_opened = function() {
                    return nav.isOpen();
                };
                _.open_menu = function() {
                    nav.open();
                };
                _.close_menu = function() {
                    nav.close();
                };
            });


            _.pages = [
                {
                    name: '主页',
                    icon: 'home',
                    view: 'home',
                },
                {
                    name: '用户',
                    icon: 'account-multiple',
                    view: 'list',
                    role: '信息部管理员',
                    list: api.user_list(),
                    list_text: {
                        major: item => item.name,
                        desc : item => item.role,
                        minor: item => item.username,
                        menu : item => `用户名：${item.username}`,
                    },
                    add: {
                        inputs: [
                            {
                                id: 'name',
                                label: "姓名",
                                type: "text",
                                icon: 'account-clipboard',
                            },
                            {
                                id: 'role',
                                label: "角色",
                                selections: api.roles,
                                icon: 'account-convert',
                            },
                            {
                                id: 'username',
                                label: "用户名",
                                type: "text",
                                icon: 'account-multiple',
                            },
                            {
                                id: 'password',
                                label: "密码",
                                type: "password",
                                icon: 'account-key',
                            },
                        ],
                        action: function(values, close) {
                            _.set_busy();
                            api.user_add(values.username,
                                         values.password,
                                         values.role,
                                         values.name,
                                         function(err) {
                                if (err != null) {
                                    _.set_idle();
                                    popup(err);
                                }
                                else {
                                    _.set_idle();
                                    popup("用户 " + values.name + " (" + values.username + ") 添加成功");
                                    close();
                                    _.list_refresh();
                                }
                                $scope.$apply();
                            });
                        },
                    },

                    menu: [
                        {
                            name: '修改姓名',
                            icon: 'account-clipboard',
                            click: function(item, menu, event) {
                                prompt_dialog({
                                    label: '新姓名',
                                    value: item.name,
                                    icon: menu.icon,
                                    text: `${item.name}(${item.username})`,
                                    action_text: menu.name,
                                    action_style: menu.style,
                                    action: function(name) {
                                        if (item.name === name) return;
                                        _.set_busy();
                                        api.user_name(item.id, name, function(err) {
                                            if (err != null) {
                                                _.set_idle();
                                                popup(err);
                                            }
                                            else {
                                                if (item.username === _.username) {
                                                    _.set_busy("姓名修改成功。请重新登录。");
                                                    setTimeout(api.login, 4000);
                                                }
                                                else {
                                                    _.set_idle();
                                                    item.name = name;
                                                    popup(item.username + " 的姓名已修改为：" + name);
                                                }
                                            }
                                            $scope.$apply();
                                        });
                                    },
                                }, event.target);
                            },
                        },
                        {
                            name: '修改密码',
                            icon: 'account-key',
                            style: 'md-primary',
                            disabled: 'item.username === app.username',
                            click: function(item, menu, event) {
                                prompt_dialog({
                                    label: '新密码',
                                    type: 'password',
                                    icon: menu.icon,
                                    text: `${item.name}(${item.username})`,
                                    action_text: menu.name,
                                    action_style: menu.style,
                                    action: function(pwd) {
                                        _.set_busy();
                                        api.user_password(item.id, pwd, function(err) {
                                            if (err != null) {
                                                _.set_idle();
                                                popup(err);
                                            }
                                            else {
                                                _.set_idle();
                                                popup(item.username + " (" + item.name + ") 的密码修改成功");
                                            }
                                            $scope.$apply();
                                        });
                                    },
                                }, event.target);
                            },
                        },
                        {
                            name: '修改角色',
                            icon: 'account-convert',
                            style: 'md-warn',
                            disabled: 'item.username === app.username',
                            click: function(item, menu, event) {
                                prompt_dialog({
                                    selections: _.roles,
                                    value: item.role,
                                    icon: menu.icon,
                                    text: `${item.name}(${item.username})`,
                                    action_text: menu.name,
                                    action_style: menu.style,
                                    action: function(role) {
                                        if (item.role === role) return;
                                        _.set_busy();
                                        api.user_role(item.id, role, function(err) {
                                            if (err != null) {
                                                _.set_idle();
                                                popup(err);
                                            }
                                            else {
                                                _.set_idle();
                                                item.role = role;
                                                popup(item.username + " (" + item.name + ") 现在是 " + role);
                                            }
                                            $scope.$apply();
                                        });
                                    },
                                }, event.target);
                            },
                        },
                        {
                            name: '离职',
                            icon: 'cancel',
                            style: 'md-accent',
                            disabled: 'item.username === app.username',
                            click: function(item, menu, event) {
                                prompt_dialog({
                                    text: `确定将 ${item.name}(${item.username}) 标记为离职？此操作将无法撤销。`,
                                    action_text: menu.name,
                                    action: function() {
                                        _.set_busy();
                                        api.user_leave(item.id, err => {
                                            if (err != null) {
                                                _.set_idle();
                                                popup(err);
                                            }
                                            else {
                                                _.set_idle();
                                                popup(`${item.name}(${item.username}) 已离职`);
                                                _.list_refresh();
                                            }
                                            $scope.$apply();
                                        });
                                    },
                                }, event.target);
                            },
                        },
                    ],
                },
                {
                    name: '业务',
                    icon: 'trending-up',
                    view: 'list',
                    role: '销售部经理',
                    list: api.sale_list(),
                    list_text: {
                        major: item => `￥${item.budget}`,
                        desc : item => item.approval == null || item.approval === "" ? item.purpose : item.approval,
                        minor: item => item.approval == null ? "" : item.approval === "" ? "已批准" : "已拒绝",
                        menu : item => `${item.applicant} 申请于 ${item.date}` + (item.approval == null || item.approval === "" ? "" : `，${item.purpose}`),
                        style: item => item.approval == null ? "" : item.approval === "" ? "color-yes" : "color-no",
                    },
                    menu: [
                        {
                            name: '批准',
                            icon: 'check',
                            style: 'md-primary',
                            disabled: 'item.approval != null',
                            click: function(item, menu, event) {
                                prompt_dialog({
                                    text: "确定？",
                                    action_text: menu.name,
                                    action_style: menu.style,
                                    action: function() {
                                        _.set_busy();
                                        api.sale_approve(item.id, err => {
                                            if (err != null) {
                                                _.set_idle();
                                                popup(err);
                                            }
                                            else {
                                                _.set_idle();
                                                popup(`已批准 ${item.applicant} 的 ￥${item.budget} 业务`);
                                                item.approval = "";
                                            }
                                            $scope.$apply();
                                        }, _.list_refresh);
                                    },
                                }, event.target);
                            },
                        },
                        {
                            name: '拒绝',
                            icon: 'close',
                            style: 'md-accent',
                            disabled: 'item.approval != null',
                            click: function(item, menu, event) {
                                prompt_dialog({
                                    text: `${item.applicant} 的 ￥${item.budget} 的业务：${item.purpose}`,
                                    label: "理由",
                                    icon: 'comment',
                                    action_text: menu.name,
                                    action_style: menu.style,
                                    action: function(reason) {
                                        _.set_busy();
                                        api.sale_reject(item.id, reason, err => {
                                            if (err != null) {
                                                _.set_idle();
                                                popup(err);
                                            }
                                            else {
                                                _.set_idle();
                                                popup(`拒绝了 ${item.applicant} 的 ￥${item.budget} 业务：${reason}`);
                                                item.approval = reason;
                                            }
                                            $scope.$apply();
                                        }, _.list_refresh);
                                    },
                                }, event.target);
                            },
                        },
                        {
                            name: '活动记录',
                            icon: 'list-ordered',
                            disabled: 'item.approval !== ""',
                            click: function(item) {
                                var sale = item.id;
                                _.page_select({
                                    name: `活动`,
                                    view: 'list',
                                    list: api.sale_activity_list(sale),
                                    list_text: {
                                        major: item => `￥${item.cost}`,
                                        desc : item => item.activity,
                                        minor: item => '',
                                        menu : item => `添加于 ${item.date}`,
                                    },
                                    back: true,
                                });
                            },
                        },
                    ],
                },
                {
                    name: '业务',
                    icon: 'trending-up',
                    view: 'list',
                    role: '销售部业务员',
                    list: api.sale_list_self(),
                    list_text: {
                        major: item => item.approval == null ? "待审批" : item.approval === "" ? "已批准" : "被拒绝",
                        desc : item => item.approval == null || item.approval === "" ? item.purpose : item.approval,
                        minor: item => `￥${item.budget}`,
                        menu : item => `申请于 ${item.date}` + (item.approval == null || item.approval === "" ? "" : `，${item.purpose}`),
                        style: item => item.approval == null ? "" : item.approval === "" ? "color-yes" : "color-no",
                    },
                    add: {
                        inputs: [
                            {
                                id: 'budget',
                                label: '预算（人民币）',
                                type: 'number',
                                icon: 'cash',
                                min: 0,
                                max: 99999999.99,
                                step: 0.01,
                            },
                            {
                                id: 'purpose',
                                label: '梗概',
                                type: 'text',
                                icon: 'comment',
                            },
                        ],
                        action: function(values, close) {
                            _.set_busy();
                            api.sale_add(values.purpose,
                                         values.budget,
                                         function(err) {
                                if (err != null) {
                                    _.set_idle();
                                    popup(err);
                                }
                                else {
                                    _.set_idle();
                                    popup("业务添加成功");
                                    close();
                                    _.list_refresh();
                                }
                                $scope.$apply();
                            });
                        },
                    },
                    menu: [
                        {
                            name: '活动记录',
                            icon: 'list-ordered',
                            disabled: 'item.approval !== ""',
                            click: function(item) {
                                var sale = item.id;
                                _.page_select({
                                    name: `活动`,
                                    view: 'list',
                                    list: api.sale_activity_list_self(sale),
                                    list_text: {
                                        major: item => `￥${item.cost}`,
                                        desc : item => item.activity,
                                        minor: item => '',
                                        menu : item => `添加于 ${item.date}`,
                                    },
                                    back: true,
                                    add: {
                                        inputs: [
                                            {
                                                id: 'cost',
                                                label: '花费（人民币）',
                                                type: 'number',
                                                icon: 'cash',
                                                min: 0,
                                                max: 99999999.99,
                                                step: 0.01,
                                            },
                                            {
                                                id: 'activity',
                                                label: '梗概',
                                                type: 'text',
                                                icon: 'comment',
                                            },
                                        ],
                                        action: function(values, close) {
                                            _.set_busy();
                                            api.sale_activity_add(sale,
                                                         values.activity,
                                                         values.cost,
                                                         function(err) {
                                                if (err != null) {
                                                    _.set_idle();
                                                    popup(err);
                                                }
                                                else {
                                                    _.set_idle();
                                                    popup("活动添加成功");
                                                    close();
                                                    _.list_refresh();
                                                }
                                                $scope.$apply();
                                            });
                                        },
                                    },
                                });
                            },
                        },
                        {
                            name: '取消申请',
                            icon: 'cancel',
                            style: 'md-accent',
                            disabled: 'item.approval != null',
                            click: function(item, menu, event) {
                                prompt_dialog({
                                    text: "确定？",
                                    action_text: menu.name,
                                    action_style: menu.style,
                                    action: function() {
                                        _.set_busy();
                                        api.sale_cancel(item.id, err => {
                                            if (err != null) {
                                                _.set_idle();
                                                popup(err);
                                            }
                                            else {
                                                _.set_idle();
                                                popup(`￥${item.budget} 的业务已取消：${item.purpose}`);
                                                item.approval = '取消';
                                            }
                                            $scope.$apply();
                                        }, _.list_refresh);
                                    },
                                }, event.target);
                            },
                        },
                    ],
                },
                {
                    name: '工单',
                    icon: 'receipt',
                    view: 'list',
                    role: '售后部经理',
                    list: api.ticket_list(),
                    list_text: {
                        major: item => item.customer,
                        desc : item => item.complaint,
                        minor: item => item.assignee == null ? "未指派" : item.assignee + (item.result == null ? "" : item.result),
                        menu : item => item.detail,
                        style: item => item.result == null ? '' : item.result === '成功' ? 'color-yes' : item.result === '失败' ? 'color-no2' : 'color-no',
                    },
                },
                {
                    name: '工单',
                    icon: 'receipt',
                    view: 'list',
                    role: '售后部业务员',
                    list: api.ticket_list_self(),
                    list_text: {
                        major: item => item.customer,
                        desc : item => item.complaint,
                        minor: item => item.result == null ? item.contact : item.result,
                        menu : item => item.result == null ? item.contact : item.result + (item.result === '成功' ? '' : '：' + item.detail),
                        style: item => item.result == null ? '' : item.result === '成功' ? 'color-yes' : item.result === '失败' ? 'color-no2' : 'color-no',
                    },
                    menu: [
                        {
                            name: '标记为成功',
                            icon: 'check',
                            style: 'md-primary',
                            disabled: 'item.result != null',
                            click: function(item, menu, event) {
                                prompt_dialog({
                                    text: "确定？",
                                    action_text: menu.name,
                                    action_style: menu.style,
                                    action: function() {
                                        _.set_busy();
                                        api.ticket_done(item.id, err => {
                                            if (err != null) {
                                                _.set_idle();
                                                popup(err);
                                            }
                                            else {
                                                _.set_idle();
                                                popup(`${item.customer} 的工单处理成功`);
                                                item.result = '成功';
                                            }
                                            $scope.$apply();
                                        }, _.list_refresh);
                                    },
                                }, event.target);
                            },
                        },
                        {
                            name: '标记为失败',
                            icon: 'close',
                            style: 'md-warn',
                            disabled: 'item.result != null',
                            click: function(item, menu, event) {
                                prompt_dialog({
                                    text: `${item.customer}：${item.complaint}`,
                                    label: "说明",
                                    icon: 'comment',
                                    action_text: menu.name,
                                    action_style: menu.style,
                                    action: function(detail) {
                                        _.set_busy();
                                        api.ticket_fail(item.id, detail, err => {
                                            if (err != null) {
                                                _.set_idle();
                                                popup(err);
                                            }
                                            else {
                                                _.set_idle();
                                                popup(`${item.customer} 的工单标记为失败：${detail}`);
                                                item.result = '失败';
                                                item.detail = detail;
                                            }
                                            $scope.$apply();
                                        }, _.list_refresh);
                                    },
                                }, event.target);
                            },
                        },
                        {
                            name: '放弃该工单',
                            icon: 'cancel',
                            style: 'md-accent',
                            disabled: 'item.result != null',
                            click: function(item, menu, event) {
                                prompt_dialog({
                                    text: `${item.customer}：${item.complaint}`,
                                    label: "理由",
                                    icon: 'comment',
                                    action_text: menu.name,
                                    action_style: menu.style,
                                    action: function(detail) {
                                        _.set_busy();
                                        api.ticket_waive(item.id, detail, err => {
                                            if (err != null) {
                                                _.set_idle();
                                                popup(err);
                                            }
                                            else {
                                                _.set_idle();
                                                popup(`已放弃 ${item.customer} 的工单：${detail}`);
                                                item.result = '放弃';
                                                item.detail = detail;
                                            }
                                            $scope.$apply();
                                        }, _.list_refresh);
                                    },
                                }, event.target);
                            },
                        },
                    ],
                },
                {
                    name: '工单',
                    icon: 'receipt',
                    view: 'list',
                    role: '售后部信息员',
                    list: api.ticket_list_latest(),
                    list_text: {
                        major: item => item.customer,
                        desc : item => item.complaint,
                        minor: item => item.result == null ? "" : item.result,
                        menu : item => item.detail,
                        style: item => item.result == null ? '' : item.result === '成功' ? 'color-yes' : item.result === '失败' ? 'color-no2' : 'color-no',
                    },
                    add: {
                        inputs: [
                            {
                                id: 'customer',
                                label: "客户称呼",
                                type: "text",
                                icon: 'account-clipboard',
                            },
                            {
                                id: 'contact',
                                label: "联系方式",
                                type: "text",
                                icon: 'motorbike',
                            },
                            {
                                id: 'complaint',
                                label: "详情概述",
                                type: "text",
                                icon: 'comment-more',
                            },
                        ],
                        action: function(values, close) {
                            _.set_busy();
                            api.ticket_add(values.complaint,
                                         values.customer,
                                         values.contact,
                                         function(err) {
                                if (err != null) {
                                    _.set_idle();
                                    popup(err);
                                }
                                else {
                                    _.set_idle();
                                    popup(`${values.customer} 的工单添加成功`);
                                    close();
                                    _.list_refresh();
                                }
                                $scope.$apply();
                            });
                        },
                    },
                    menu: [
                        {
                            name: '指派业务员',
                            icon: 'account-network',
                            style: 'md-primary',
                            click: function(item) {
                                var ticket = item.id;
                                _.page_select({
                                    name: '可指派业务员',
                                    view: 'list',
                                    list: api.ticket_list_free(),
                                    list_text: {
                                        major: item => item.name,
                                        desc : item => '',
                                        minor: item => '',
                                        menu : item => item.name,
                                    },
                                    back: true,
                                    menu: [
                                        {
                                            name: '指派',
                                            icon: 'account-network',
                                            style: 'md-primary',
                                            click: function(item) {
                                                console.log(ticket, item);
                                                _.set_busy();
                                                api.ticket_assign(ticket, item.id, err => {
                                                    if (err != null) {
                                                        _.set_idle();
                                                        popup(err);
                                                    }
                                                    else {
                                                        _.set_idle();
                                                        popup(`${item.name} 已指派`);
                                                        _.page_back();
                                                        _.list_refresh();
                                                    }
                                                    $scope.$apply();
                                                }, _.list_refresh);
                                            },
                                        }
                                    ],
                                });
                            },
                        }
                    ],
                },
            ];

            _.page_select = function(page) {
                if (_.page === page) return;
                if (_.page != null && _.page.fini) _.page.fini(_.page);
                if (page.init) page.init(page);
                page.old_page = _.page;
                _.view = page.view;
                _.page = page;
                _.close_menu();
            };
            _.page_select(_.pages[0]);

            _.page_is = function(page) {
                return (_.page === page);
            };

            _.view_is = function(view) {
                return (_.view === view);
            };

            _.page_back = function() {
                if (_.page.old_page == null) return;
                _.page_select(_.page.old_page);
            };

            _.accessible = function(page) {
                if (page.role == null) return true;
                return (page.role === _.role);
            };

            _.toolbar_icons = [
                {
                    name: '修改我的密码',
                    icon: 'account-key',
                    style: '',
                    style_collapse: 'md-primary',
                    prompt: {
                        label: "新密码",
                        type: "password",
                        text: _.role + " " + _.name + " " + _.username,
                        action: function(pwd) {
                            _.set_busy();
                            api.user_password_self(pwd, function(err) {
                                if (err != null) {
                                    _.set_idle();
                                    popup(err);
                                }
                                else {
                                    _.set_busy("密码修改成功。需要重新登录。");
                                    setTimeout(api.login, 4000);
                                }
                                $scope.$apply();
                            });
                        },
                    },
                },
                {
                    divider: true,
                },
                {
                    name: '登出所有设备',
                    icon: 'account-alert',
                    style: 'md-warn md-hue-3',
                    style_collapse: 'md-warn',
                    click: function() {
                        _.set_busy();
                        api.user_revoke_self(api.login);
                    },
                },
                {
                    name: '切换用户',
                    icon: 'account-switch',
                    style: '',
                    style_collapse: '',
                    click: function() {
                        _.set_busy();
                        api.login();
                    },
                },
            ];
            _.toolbar_icon_click = function(icon, event) {
                if (icon.view != null) _.page_select(icon);
                else if (icon.prompt != null) {
                    icon.prompt.action_text = icon.name;
                    icon.prompt.icon = icon.icon;
                    prompt_dialog(icon.prompt, event.target);
                }
                else icon.click(event);
            };


            _.loading = false;
            var list = {};
            _.list_refresh = function() {
                list = {
                    api: list.api,
                    next: list.api(),
                    cache: [],
                    done: false,
                };
            };
            var list_load = function() {
                var lst = list;
                if (lst.done) return;
                if (_.loading) return;
                _.loading = true;
                if (!$scope.$$phase) $scope.$apply();
                lst.next(function(items) {
                    if (items == null) {
                        popup('载入失败');
                        lst.done = true;
                    }
                    else {
                        if (items.length < 10) lst.done = true;
                        items.forEach(function(item) { lst.cache.push(item); });
                    }
                    _.loading = false;
                    $scope.$apply();
                });
            };
            var items = {};
            items.getItemAtIndex = function(i) {
                if (i < list.cache.length) return list.cache[i];
                list_load();
            };
            items.getLength = function() {
                return list.cache.length + (list.done ? 0 : 1);
            };
            _.list_items = function() {
                if (_.page.list == null) return;
                if (list.api !== _.page.list) {
                    list.api = _.page.list;
                    _.list_refresh();
                }
                return items;
            };
            _.list_add = function(ev, page) {
                $mdDialog.show({
                    templateUrl: 'form-dialog',
                    clickOutsideToClose: true,
                    controller: 'form-dialog-controller as dialog',
                    openFrom: ev.target,
                    locals: { info: page.add, action_text: `添加${page.name}` },
                });
            };
        });

        app.controller('prompt-dialog-controller', function($mdDialog, info) {
            var _ = this;

            Object.assign(_, info);
            if (_.action_style == null) _.action_style = "md-primary";
            if (_.type == null) _.type = "text";

            _.close = function() {
                $mdDialog.hide();
            };

            _.action = function() {
                info.action(_.value);
                _.close();
            };
        });

        app.controller('form-dialog-controller', function($mdDialog, info, action_text) {
            var _ = this;

            _.inputs = info.inputs;
            _.values = {};
            _.action_text = action_text;

            _.close = function() {
                $mdDialog.hide();
            };

            _.action = function() {
                info.action(_.values, _.close);
            };
        });
    };
});

